import axios from "axios"
import { MessageBox,Message,Loading } from "element-ui"
import storage from "./storage"
import nprogress from "nprogress"
import 'nprogress/nprogress.css'

let http = axios.create({
    withCredentials:true,
    baseURL:"/api",
    timeout:1000 * 15,
})

let fullScreenLoading = null;
http.interceptors.request.use(config => {
    nprogress.start()

    let token = storage.get("sasa-token");
    config.headers['authorization'] = token;
    console.log(config);
     if(config.url.indexOf('login') !== -1 || config.url.indexOf('wechatLogin') !== -1){
        fullScreenLoading = Loading.service({
            lock: true,
            text: '加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
        })
     }
 
    return config  
})

http.interceptors.response.use(config => {
    nprogress.done() 
    if(fullScreenLoading){
        fullScreenLoading.close()
        fullScreenLoading = null;
    }
    let { state , msg } = config.data
    if(!state && config.config.url !== "/order/query_order_status"){
        MessageBox({
            message:msg,
            title:'错误提示',
            type:'error'
        })
    }
    let { code } = config.data;
    if(code === '10022' || code === '1004'){
        Message.error('登入过期,请重新登入')
        storage.rm('sasa-token')
        location.reload()
    }
    return config 
})

export default http;